package com.my.ph.util;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

@Slf4j
public class GenerateImageUtil {

    public static String generateImage(String videoPath, Integer secs){
        File tempFile = FileUtil.createTempFile(".png", true);
        try (FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videoPath)){
            ff.start();
            Frame f;
            //传入的参数是秒，这里需要处理的时间戳是按微秒走的,需要转换一下
            long targetFrameNum = secs * 1000 * 1000;
            ff.setTimestamp(targetFrameNum);
            //根据传入的时间戳，抓取指定时间的视频关键帧
            f = ff.grabImage();
            if (f != null) {
                Java2DFrameConverter converter = new Java2DFrameConverter();
                BufferedImage bufferedImage = converter.getBufferedImage(f);
                ImageIO.write(bufferedImage, "jpg", tempFile);
            }
            ff.stop();
        } catch (IOException e) {
            log.error("{}", e.getMessage(), e);
        }
        return tempFile.getPath();
    }

}
